import json
import cv2
import numpy as np
import os

from torch.utils.data import Dataset


class MyDataset(Dataset):
    def __init__(self, input_dir):
        self.data = []
        self.json_dir = os.path.join(input_dir, 'caption')
        self.faceimg_dir = os.path.join(input_dir, 'aligned_masked')
        self.cropimg4pose_dir = os.path.join(input_dir, 'cropimg4pose')
        self.poseimg_dir = os.path.join(input_dir, 'poseimg')
        for filename in os.listdir(self.json_dir):
            filepath = os.path.join(self.json_dir, filename)
            with open(filepath, 'r', encoding='utf-8') as f:
                json_data = json.load(f)
                self.data.append(json_data)
            f.close()
            

    def __len__(self):
        return len(self.data)

    def __getitem__(self, idx):
        item = self.data[idx]

        img_filename = item['imgs'][0]
        prompt = item['captions'][0]

        source = cv2.imread(self.poseimg_dir + '/' + img_filename)
        target = cv2.imread(self.cropimg4pose_dir + '/' + img_filename)
        face = cv2.imread(self.faceimg_dir + '/' + img_filename)

        # Do not forget that OpenCV read images in BGR order.
        source = cv2.cvtColor(source, cv2.COLOR_BGR2RGB)
        target = cv2.cvtColor(target, cv2.COLOR_BGR2RGB)
        face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)

        # Normalize source images to [0, 1].
        source = source.astype(np.float32) / 255.0

        # Normalize target and face images to [-1, 1].
        target = (target.astype(np.float32) / 127.5) - 1.0
        face = (face.astype(np.float32) / 127.5) - 1.0

        return dict(jpg=target, txt=prompt, hint=source, face=face)

